<template>
  <div class="workorder-approve-page">
    <div class="banner">
      <div class="banner-content">
        <img class="logo" src="@/assets/photoes/logo.jpg" alt="logo" />
        <div class="banner-title">铁岭电网无人机管理平台</div>
      </div>
      <img class="banner-bg" src="@/assets/background.png" alt="banner" />
    </div>

    <div class="approve-section">
      <div class="back-btn-section">
        <el-button class="back-btn" :icon="ArrowLeft" @click="goBack"
          >返回</el-button
        >
      </div>

      <div class="approve-container">
        <div class="approve-header">
          <h2 class="approve-title">工单审批详情</h2>
          <div class="status-badge" :class="statusClass(workorderData.status)">
            {{ statusText(workorderData.status) }}
          </div>
        </div>

        <el-skeleton
          v-if="loading"
          :loading="loading"
          :rows="8"
          style="padding: 20px"
        ></el-skeleton>

        <div v-else class="workorder-details">
          <div class="detail-grid">
            <div class="detail-item">
              <div class="detail-label">
                <i class="el-icon-document"></i>
                任务名称
              </div>
              <div class="detail-value">
                {{ workorderData.taskName || "暂无" }}
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">
                <i class="el-icon-location"></i>
                作业地点
              </div>
              <div class="detail-value">
                {{ workorderData.address || "暂无" }}
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">
                <i class="el-icon-time"></i>
                预计作业时间
              </div>
              <div class="detail-value">
                {{
                  formatDateTime(workorderData.estimatedHomeworkTime) || "暂无"
                }}
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">
                <i class="el-icon-warning"></i>
                优先级
              </div>
              <div class="detail-value">
                <el-tag
                  :type="getPriorityType(workorderData.priority)"
                  size="small"
                >
                  {{ workorderData.priority || "暂无" }}
                </el-tag>
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">
                <i class="el-icon-document"></i>
                关联项目
              </div>
              <div class="detail-value">
                {{ workorderData.projectInfo || "暂无" }}
              </div>
            </div>

            <div class="detail-item">
              <div class="detail-label">
                <i class="el-icon-cpu"></i>
                无人机名称
              </div>
              <div class="detail-value">
                {{ workorderData.uavName || "暂无" }}
              </div>
            </div>

            <div class="detail-item full-width">
              <div class="detail-label">
                <i class="el-icon-edit"></i>
                任务描述
              </div>
              <div class="detail-value description-text">
                {{ workorderData.taskDescription || "暂无任务描述" }}
              </div>
            </div>

            <div class="detail-item full-width" v-if="workorderData.file">
              <div class="detail-label">
                <i class="el-icon-document"></i>
                附件
              </div>
              <div class="detail-value">
                <el-button type="primary" size="small" @click="downloadFile">
                  <i class="el-icon-download"></i>
                  下载附件
                </el-button>
              </div>
            </div>
          </div>

          <div class="approve-actions">
            <div class="remarks-section">
              <div class="remarks-label">
                <i class="el-icon-edit"></i>工单审批备注
              </div>
              <el-input
                v-model="notes"
                type="textarea"
                placeholder="请输入工单审批备注（可选）"
                :rows="3"
                maxlength="200"
                show-word-limit
                class="remarks-input"
              />
            </div>
            <div class="action-buttons">
              <el-button
                type="success"
                size="large"
                @click="handleApprove"
                :loading="approving"
                class="approve-btn"
              >
                <i class="el-icon-check"></i>
                通过
              </el-button>
              <el-button
                type="danger"
                size="large"
                @click="handleReject"
                :loading="rejecting"
                class="reject-btn"
              >
                <i class="el-icon-close"></i>
                驳回
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
const loading = ref(true);
const approving = ref(false);
const rejecting = ref(false);
const notes = ref("");

const workorderData = reactive({
  id: "",
  taskName: "",
  address: "",
  estimatedHomeworkTime: "",
  priority: "",
  projectInfo: "",
  taskDescription: "",
  uavId: "",
  uavName: "",
  file: "",
  status: "",
  notes: "",
  remarks: "",
  createUser: "",
});

function statusText(status) {
  if (status === "0") return "待审批";
  if (status === "1") return "已通过";
  if (status === "2") return "已驳回";
  return "未知状态";
}

function statusClass(status) {
  if (status === "0") return "pending";
  if (status === "1") return "approved";
  if (status === "2") return "rejected";
  return "";
}

function getPriorityType(priority) {
  if (priority === "高") return "danger";
  if (priority === "中") return "warning";
  if (priority === "低") return "info";
  return "info";
}

function formatDateTime(dateTime) {
  if (!dateTime) return "";
  try {
    const date = new Date(dateTime);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return dateTime;
  }
}

function downloadFile() {
  if (workorderData.file) {
    // 创建下载链接
    const link = document.createElement("a");
    link.href = `data:application/octet-stream;base64,${workorderData.file}`;
    link.download = "工单附件";
    link.click();
  }
}

function goBack() {
  router.push({
    path: "/workorder",
    query: { tab: "approve" },
  });
}

async function fetchWorkorderDetail() {
  try {
    const workorderId = route.query.id;
    if (!workorderId) {
      ElMessage.error("工单ID不能为空");
      return;
    }

    const res = await axios.get(
      `/tielingpowergriduavservice/task/${workorderId}`
    );

    if (res.data && res.data.code === 200) {
      Object.assign(workorderData, res.data.data);
    } else {
      ElMessage.error(res.data?.message || "获取工单详情失败");
    }
  } catch (e) {
    ElMessage.error("请求工单详情异常");
  } finally {
    loading.value = false;
  }
}

async function handleApprove() {
  try {
    approving.value = true;
    const formData = new FormData();
    formData.append("id", workorderData.id);
    formData.append("status", "1");
    formData.append("notes", notes.value);
    const res = await axios.post(
      "/tielingpowergriduavservice/task/update",
      formData
    );
    if (res.data.code === 200) {
      ElMessage.success("审批通过成功");
      workorderData.status = "1";
      workorderData.notes = notes.value;
      router.push({ path: "/workorder", query: { tab: "approve" } });
    } else {
      ElMessage.error("审批失败：" + res.data.msg);
    }
  } catch (e) {
    ElMessage.error("审批操作异常");
  } finally {
    approving.value = false;
  }
}

async function handleReject() {
  try {
    rejecting.value = true;
    const formData = new FormData();
    formData.append("id", workorderData.id);
    formData.append("status", "2");
    formData.append("notes", notes.value);
    const res = await axios.post(
      "/tielingpowergriduavservice/task/update",
      formData
    );
    if (res.data.code === 200) {
      ElMessage.success("拒绝成功");
      workorderData.status = "2";
      workorderData.notes = notes.value;
      router.push({ path: "/workorder", query: { tab: "approve" } });
    } else {
      ElMessage.error("拒绝失败：" + res.data.msg);
    }
  } catch (e) {
    ElMessage.error("拒绝操作异常");
  } finally {
    rejecting.value = false;
  }
}

onMounted(() => {
  fetchWorkorderDetail();
});
</script>

<style scoped>
.workorder-approve-page {
  min-height: 100vh;
  background: #f8fafd;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.banner {
  position: relative;
  width: 100%;
  height: 220px;
  background: #199893;
  overflow: hidden;
  display: flex;
  align-items: flex-end;
}

.banner-content {
  position: absolute;
  left: 60px;
  top: 40px;
  z-index: 2;
  display: flex;
  align-items: center;
}

.logo {
  width: 200px;
  height: 50px;
  margin-right: 18px;
}

.banner-title {
  color: #fff;
  font-size: 28px;
  font-weight: bold;
  letter-spacing: 2px;
}

.banner-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0.7;
}

.approve-section {
  width: 90%;
  margin: 60px 30px;
  padding: 0;
}

.back-btn-section {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.back-btn {
  font-size: 16px;
  padding: 10px 28px;
  border-radius: 22px;
  background: linear-gradient(90deg, #199893 0%, #4fd1c5 100%);
  color: #fff;
  box-shadow: 0 2px 12px rgba(25, 152, 147, 0.1);
  border: none;
  transition: background 0.2s, box-shadow 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.back-btn:hover {
  background: linear-gradient(90deg, #12706b 0%, #199893 100%);
  box-shadow: 0 4px 16px rgba(25, 152, 147, 0.18);
}

.approve-container {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(25, 152, 147, 0.08);
  padding: 40px;
  min-height: 600px;
  /* width: 100%; */
}

.approve-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f1f5f9;
}

.approve-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  display: flex;
  align-items: center;
}

.approve-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 24px;
  background-color: #3498db;
  margin-right: 12px;
  border-radius: 2px;
}

.status-badge {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  color: #fff;
}

.status-badge.pending {
  background: linear-gradient(90deg, #f39c12 0%, #e67e22 100%);
}

.status-badge.approved {
  background: linear-gradient(90deg, #27ae60 0%, #2ecc71 100%);
}

.status-badge.rejected {
  background: linear-gradient(90deg, #e74c3c 0%, #c0392b 100%);
}

.workorder-details {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.detail-item {
  background: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.detail-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-label {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
  margin-bottom: 8px;
}

.detail-label i {
  margin-right: 8px;
  font-size: 16px;
  color: #199893;
}

.detail-value {
  font-size: 16px;
  color: #1e293b;
  font-weight: 500;
  line-height: 1.5;
}

.description-text {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #475569;
}

.approve-actions {
  display: flex;
  flex-direction: column; /* Changed to column for remarks and buttons */
  align-items: flex-start; /* Align items to the start */
  padding-top: 40px;
  border-top: 2px solid #f1f5f9;
}

.remarks-section {
  width: 100%;
  /* max-width: 600px; */
  margin-bottom: 24px;
}
.remarks-label {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 12px;
}
.remarks-label i {
  margin-right: 8px;
  font-size: 18px;
  color: #199893;
}
.remarks-input {
  width: 100%;
}

.action-buttons {
  display: flex;
  justify-content: center;
  width: 100%;
  gap: 24px;
}

.approve-btn {
  padding: 12px 32px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(90deg, #27ae60 0%, #2ecc71 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
  transition: all 0.3s ease;
}

.approve-btn:hover {
  background: linear-gradient(90deg, #229954 0%, #27ae60 100%);
  box-shadow: 0 6px 16px rgba(39, 174, 96, 0.4);
  transform: translateY(-2px);
}

.reject-btn {
  padding: 12px 32px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(90deg, #e74c3c 0%, #c0392b 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
  transition: all 0.3s ease;
}

.reject-btn:hover {
  background: linear-gradient(90deg, #c0392b 0%, #a93226 100%);
  box-shadow: 0 6px 16px rgba(231, 76, 60, 0.4);
  transform: translateY(-2px);
}

.content {
  overflow-y: auto;
  overflow-x: hidden;
  max-height: calc(100vh - 100px);
}

@media (max-width: 768px) {
  .approve-section {
    padding: 0 20px;
  }

  .approve-container {
    padding: 30px 20px;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
    gap: 16px;
  }

  .approve-btn,
  .reject-btn {
    width: 100%;
  }
}
</style>
